//
//  ZLSwapMenu.swift
//  ZLSwapMenu
//
//  Created by 赵振磊 on 2023/1/11.
//

import UIKit

public protocol ZLSwapMenuDelegate {
    /// 已经发生移动（用于同步数据）
    func didMove(from: Int, to: Int)
    /// 移动完成刷新列表（用于刷新cell状态）
    func didMoveReload(cell: UICollectionViewCell?, index: Int)
}

public class ZLSwapMenu: UICollectionView {
    /// 代理
    public var swapDelegate: ZLSwapMenuDelegate?
    /// 当前下标
    var currentIndex: Int = 0
    /// 当前cell
    var currentCell: UICollectionViewCell?
    /// cell尺寸
    public var itemSize: CGSize = CGSize.zero
    /// 正在移动的cell的蒙版
    lazy var topImage: UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()
    public override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        let longTap = UILongPressGestureRecognizer(target: self, action: #selector(longTapAction(_:)));
        self.addGestureRecognizer(longTap)
        self.addSubview(self.topImage)
    }
    /// 长按编辑
    @objc func longTapAction(_ tap: UILongPressGestureRecognizer) {
        if tap.state != .began && tap.state != .changed {
            self.topImage.isHidden = true
            self.currentCell!.isHidden = false
        }
        let point = tap.location(in: self)
        guard let indexPath = self.indexPathForItem(at: point) else {
            self.topImage.center = point
            return
        }
        guard let cell = self.cellForItem(at: indexPath) else { return }
        switch tap.state {
        case .began:
            self.currentCell = cell
            self.topImage.image = self.currentCell!.zl_shotImage()
            self.topImage.frame = cell.frame
            self.topImage.center = point
            self.topImage.isHidden = false
            self.currentCell?.isHidden = true
            self.currentIndex = indexPath.row
            break
        case .changed:
            self.topImage.center = point
            if indexPath.row == self.currentIndex {
                break
            }
            let changLine = self.currentCell!.center.y - cell.center.y
            if changLine < 0 {  // 上移动到下
                self.move(from: indexPath.row, to: self.currentIndex)
                self.move(from: self.currentIndex + 1, to: indexPath.row)
            } else if changLine > 0 {   // 下移动到上
                self.move(from: self.currentIndex, to: indexPath.row)
                self.move(from: indexPath.row + 1, to: self.currentIndex)
            } else {    // 一行
                self.move(from: self.currentIndex, to: indexPath.row)
            }
            self.swapDelegate?.didMove(from: self.currentIndex, to: indexPath.row)
            self.currentIndex = indexPath.row
            break
        default:
            self.topImage.isHidden = true
            self.currentCell!.isHidden = false
            break
        }
    }
    /// 移动
    func move(from: Int, to: Int) {
        self.moveItem(at: IndexPath(row: from, section: 0), to: IndexPath(row: to, section: 0))
        self.swapReloadData()
        self.topImage.image = self.currentCell!.zl_shotImage()
    }
    func swapReloadData() {
        for row in 0..<self.numberOfItems(inSection: 0) {
            let indexPath = IndexPath(row: row, section: 0)
            let cell = self.cellForItem(at: indexPath)
            self.swapDelegate?.didMoveReload(cell: cell, index: row)
            cell?.isHidden = cell == self.currentCell
        }
    }
}
//MARK: 工具
extension UICollectionViewCell {
    /// 快照
    func zl_shotImage() -> UIImage {
        let hidden = isHidden
        if hidden {
            isHidden = false
        }
        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        let image = renderer.image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
        isHidden = hidden
        return image
    }
}
